package com.lm.langchain4j.adapter;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 兼容不同版本 chat/completion 方法：
 * - generate(prompt)
 * - createChatCompletion(request) 等
 *
 * 简单返回 String 文本结果。
 */
public class ChatModelAdapter {

    private final Object chatModel;
    private final Class<?> clazz;

    public ChatModelAdapter(Object chatModel) {
        this.chatModel = chatModel;
        this.clazz = chatModel.getClass();
    }

    public String generate(String prompt) {
        // 尝试常见方法
        String[] names = new String[]{"generate", "chat", "createChatCompletion", "complete", "completion"};
        for (String name : names) {
            for (Method m : clazz.getMethods()) {
                if (m.getName().equalsIgnoreCase(name)) {
                    try {
                        Object res = m.invoke(chatModel, prompt);
                        // 常见返回可能是 ChatResult / String / Map
                        if (res == null) return null;
                        if (res instanceof String) return (String) res;
                        // 尝试反射取 text/content 字段或方法
                        try {
                            Method textMethod = res.getClass().getMethod("getText");
                            Object t = textMethod.invoke(res);
                            if (t != null) return t.toString();
                        } catch (NoSuchMethodException ignored) {}
                        try {
                            Method contentMethod = res.getClass().getMethod("content");
                            Object c = contentMethod.invoke(res);
                            if (c != null) return c.toString();
                        } catch (NoSuchMethodException ignored) {}
                        // fallback to toString
                        return res.toString();
                    } catch (Throwable ignored) {}
                }
            }
        }
        throw new RuntimeException("无法调用 chatModel 的生成方法，请检查 chatModel API");
    }
}
